package com.filyar.htyd.config;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import com.filyar.htyd.common.ExceptionEnum;
import com.filyar.htyd.config.interceptor.IpBlacklistInterceptor;
import com.filyar.htyd.config.interceptor.RateLimitInterceptor;
import com.filyar.htyd.exception.ServiceException;
import com.filyar.htyd.utils.StpMobileUserUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration
public class InterceptorConfig extends WebMvcConfigurationSupport {

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/swagger-ui/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");
        super.addResourceHandlers(registry);
    }

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(ipBlacklistInterceptor())
                .addPathPatterns("/**");
        registry.addInterceptor(rateLimitInterceptor())
                .addPathPatterns("/**");
        // 注册 Sa-Token 拦截器，校验规则为 StpUtil.checkLogin() 登录校验。
        registry.addInterceptor(new SaInterceptor(handle -> {
                    SaRouter.match("/**").check(r -> {
                        if(!StpUtil.isLogin() && !StpMobileUserUtil.isLogin()) {
                            throw new ServiceException(ExceptionEnum.PLEASE_LOGIN);
                        }
                    });
                }))
                .addPathPatterns("/**");
        super.addInterceptors(registry);
    }

    @Bean
    public IpBlacklistInterceptor ipBlacklistInterceptor() {
        return new IpBlacklistInterceptor();
    }
    @Bean
    public RateLimitInterceptor rateLimitInterceptor(){
        return new RateLimitInterceptor();
    }


}
